package com.aqie.libfactory.data.helper;

import android.util.Log;

import com.aqie.libfactory.Factory;
import com.aqie.libfactory.model.api.RspModel;
import com.aqie.libfactory.model.db.User;
import com.aqie.libfactory.model.db.User_Table;
import com.aqie.libfactory.net.Network;
import com.aqie.libfactory.net.RemoteService;
import com.raizlabs.android.dbflow.sql.language.SQLite;

import java.io.IOException;

import retrofit2.Response;

public class UserHelper {

    public static User search(String id) {
        User user = findFromLocal(id);
        if (user == null) {
            return findFromNet(id);
        }
        return user;
    }

    // 从本地查询一个用户的信息
    public static User findFromLocal(String id) {
        return SQLite.select()
                .from(User.class)
                .where(User_Table.userId.eq(id))
                .querySingle();
    }

    // 从网络查询某用户的信息
    public static User findFromNet(String id) {

        RemoteService service = Network.remote();
        Response<RspModel<User>> response = null;
        try {
            response = service.talentBase(id).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        RspModel<User> body = response.body();
        if(body !=null && body.success()){
            User user = body.getData();
            // 数据库的存储并通知
            Factory.getUserCenter().dispatch(user);
            return user;
        }else {
            Log.e("UserHelper", "request fail");
        }

        return null;
    }
}
